package org.thinkinbunny.financial.service;

import java.util.Timer;
import java.util.TimerTask;

import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.broadcast.BudgetReciver;
import org.thinkinbunny.financial.util.Constant;
import org.thinkinbunny.financial.util.ServiceTimeUtil;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.widget.Toast;

public class BudgetService extends Service {

	public static final String ACTION = "org.thinkinbunny.financial.service.BudgetService";

	long timeInterval = 1000 * 60 * 1;
	boolean isStop = true, isRing = false;
	Timer timer;
	TimerTask task;
	MediaPlayer player = new MediaPlayer();
	Vibrator vibratorm;
	Handler handler;
	String msg = null, date, time;// =bundle.getString("message");

	@Override
	public void onCreate() {
		super.onCreate();

		handler = new Handler();
		timer = new Timer();

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub

		Bundle bundle = intent.getBundleExtra("msg");

		if (bundle != null) {
			// int time = bundle.getInt("time");
			msg = bundle.getString("message");
			date = bundle.getString("date");
			time = bundle.getString("time");
			isRing = bundle.getBoolean("Ring");
			ServiceTimeUtil serviceTimeUtil = new ServiceTimeUtil();
			long itime = serviceTimeUtil.getBudgetTimeRing(null, date + " "
					+ time + ":00", null);
			if (itime > 0) {
				Toast.makeText(this, time + msg, Toast.LENGTH_LONG).show();
				timeInterval = itime;
			}

		} else {
			Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
		}

		if (isStop) {

			if (task == null) {
				task = new TimerTask() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// remind();
						if (isRing) {
							DoRing();
						} else {
							remind();
						}

					}
				};
			}
			// 任务 任务推迟执行时间 任务执行的间隔
			timer.schedule(task, timeInterval, 10000);
			isStop = false;
		}
		super.onStart(intent, startId);
	}

	void DoRing() {

		Uri ringtoneUri = RingtoneManager
				.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
		try {
			player.setDataSource(this, ringtoneUri);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {

			player.setAudioStreamType(AudioManager.STREAM_ALARM);
			player.setLooping(false);
			try {
				player.prepare();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			player.start();
		}

		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// startActivity(new
				// Intent(getApplicationContext(),LoginActivity.class));
				// ShowDialog.buildMsgDialog(getApplicationContext()).show() ;
				Intent intent = new Intent(BudgetReciver.ACTION);
				intent.putExtra("message", msg);
				sendBroadcast(intent);
			}
		});
	}

	void remind() {
		vibratorm = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);
		// vibratorm.vibrate(100000);
		vibratorm.vibrate(new long[] { 100, 50, 100, 50, 100, 50, 100, 100, 50,
				100, 50, 100, 50, 100, 50, 100, 50, 100, 50, 100, 100, 50, 100,
				50, 100, 50, 100, 100, 50, 100, 50, 100, 50, 100 }, -1);

		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// startActivity(new
				// Intent(getApplicationContext(),LoginActivity.class));
				// ShowDialog.buildMsgDialog(getApplicationContext()).show() ;
				Intent intent = new Intent(BudgetReciver.ACTION);
				intent.putExtra("message", msg);
				sendBroadcast(intent);
			}
		});
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub

		return super.onUnbind(intent);

	}

	@Override
	public void onDestroy() {

		try {
			if (vibratorm != null) {
				vibratorm.cancel();
			} else if (player != null) {
				player.release();
				player.stop();
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		// if (isRing) {
		// if (player.isPlaying()) {
		// DLog.i("Ring", "stop");
		// player.stop();
		//
		// }
		// } else {
		// vibratorm.cancel();
		//
		// }
		//
		isStop = true;
		task = null;
		timer.cancel();
		SharedPreferences pref = getSharedPreferences(Constant.BUDGET_SHARE,
				Context.MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.putString("message", null);
		editor.putString("date", "");
		editor.putString("time", "");
		editor.commit();
		Toast.makeText(BudgetService.this,
				getString(R.string.ring) + msg + getString(R.string.close),
				Toast.LENGTH_LONG).show();
		super.onDestroy();
	}

}
